import 'package:flutter/material.dart';

///渐隐动画堆叠布局
class AnimatedOpacityStack extends StatelessWidget {
  ///stack内组件
  final List<Widget> children;
  ///动画显示的widget
  final Widget? animatedWidget;
  ///或者图片名字
  final String? animatedAsset;
  ///用于控制显示隐藏
  final ValueNotifier<bool> showValueNotifier;
  ///动画时长
  final Duration animateDuration;
  ///显示时长
  final Duration showDuration;
  ///结束回调
  final VoidCallback? finishCallback;

  final double? left;
  final double? top;
  final double? right;
  final double? bottom;
  final double? width;
  final double? height;

  const AnimatedOpacityStack({
    Key? key,
    required this.children,
    required this.showValueNotifier,
    this.animatedWidget,
    this.animatedAsset,
    this.animateDuration = const Duration(milliseconds: 500),
    this.showDuration = const Duration(seconds: 5),
    this.finishCallback,
    this.left,
    this.top,
    this.right,
    this.bottom,
    this.width,
    this.height,
  })  : assert(animatedWidget != null || animatedAsset != null),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        ...children,
        ValueListenableBuilder(
          valueListenable: showValueNotifier,
          builder: (context, bool value, child) {
            if (value == true) {
              //开始倒计时
              Future.delayed(showDuration).then((value) {
                finishCallback?.call();
                showValueNotifier.value = false;
              });
            }
            return Positioned(
              top: top,
              bottom: bottom,
              left: left,
              right: right,
              width: width,
              height: height,
              child: AnimatedOpacity(
                opacity: value == true ? 1.0 : 0.0,
                duration: animateDuration,
                child: animatedWidget ?? Image.asset(animatedAsset!),
              ),
            );
          },
        ),
      ],
    );
  }
}
